package qzy.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class SysAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private SysUserDetailsService sysUserDetailsService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
		
		UserDetails principal = sysUserDetailsService.loadUserByUsername(token.getName());
		
		if (principal == null) {
			throw new UsernameNotFoundException("账号不存在");
		}
		
		if (!principal.getPassword().equals(token.getCredentials())) {
			throw new BadCredentialsException("密码错误");
		}

		return new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.equals(authentication);
	}

}
